//引入相关资源包
var fs = require("fs");
var path = require("path");
var request = require("request");

/**
 * 
 * @param {*} url  网络文件url地址
 * @param {*} fileName 	文件名
 * @param {*} dir 下载到的目录
 */
function getfileByUrl(url,fileName,dir){
        console.log('------------------------------------------------')
        console.log(url)
        console.log(fileName)
        console.log(dir)
        let stream = fs.createWriteStream(path.join(dir, fileName));
        request(url).pipe(stream).on("close", function (err) {
            console.log("文件" + fileName + "下载完毕");
        });
}
 function makeDir(dirpath) {
    if (!fs.existsSync(dirpath)) {
        var pathtmp;
        dirpath.split("/").forEach(function(dirname) {
            if (pathtmp) {
                pathtmp = path.join(pathtmp, dirname);
            }
            else {　
                if(dirname){
                    pathtmp = dirname;
                }else{
                    pathtmp = "/"; 
                }
            }
            if (!fs.existsSync(pathtmp)) {
                if (!fs.mkdirSync(pathtmp)) {
                    return false;
                }
            }
        });
    }else{
        // deleteFolderFiles(dirpath);
    }
    return true;
}
/* 判断文件是否存在的函数
*@path_way, 文件路径
 */
function isFileExisted(path_way) {
    return new Promise((resolve, reject) => {
      fs.access(path_way, (err) => {
        if (err) {
            resolve(false);//"不存在"
        } else {
            resolve(true);//"存在"
        }
      })
    })
  };
  /* 判断文件是否存在的函数
*@path_way, 文件路径
 */
function unlink(path) {
    return new Promise((resolve, reject) => {

        fs.unlink(path, (err) => {
            if (err) {
                resolve(false);//"不存在"
            } else {
                resolve(true);//"存在"
            }
            console.log('删除成功');
        });
    })
  };
//   发布状态修改
  function fb(article_id,state,bt_id) {
    var axios = require("axios");
    var FormData = require("form-data");
    var data = new FormData();
    data.append("article_id", article_id);
    data.append("state", state);
    data.append("bt_id", bt_id);

    var config = {
      method: "post",
      url: "http://49.235.138.249:8082/fb",
      headers: {
        "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
        Accept: "*/*",
        Host: "49.235.138.249:8082",
        Connection: "keep-alive",
        "Content-Type":
          "multipart/form-data; boundary=--------------------------026303860367999071020502",
        ...data.getHeaders(),
      },
      data: data,
    };

    axios(config)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });
  }
module.exports  = {
    makeDir,
    getfileByUrl,
    isFileExisted,
    unlink,
    fb
}
// let picUrl = 'http://127.0.0.1:3001/demo.docx'
// let dir = 'D:\\web\\ddd'
// makeDir(dir)
// getfileByUrl(picUrl, 'demo.docx', dir)
